package com.zcy.nidavellir.multilogin.login

import android.app.Activity
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.zcy.nidavellir.multilogin.Utils.log
import com.zcy.nidavellir.multilogin.Utils.toast
import com.zcy.nidavellir.multilogin.proxy.ILogin
import java.lang.ref.WeakReference
import java.util.*

/**
 * @author:       zhaocy
 * @description:  ${DESP}
 * @date:         2018/9/29
 */
class FacebookLoginImpl(private val weakReference: WeakReference<Activity>)  : ILogin {
    private var callbackManager: CallbackManager? = null
    private val EMAIL = "email"
    private val USER_POSTS = "user_posts"
    private val PUBLIC_PROFILE = "public_profile"

    override fun action() {
        callbackManager = CallbackManager.Factory.create()
        weakReference?.get()?.let {
            LoginManager.getInstance().registerCallback(callbackManager,
                object : FacebookCallback<LoginResult> {
                    override fun onSuccess(result: LoginResult?) {
                        loginRequest(it, result?.accessToken?.token.toString())
                    }

                    override fun onCancel() {
                    }

                    override fun onError(error: FacebookException?) {
                    }

                })

            LoginManager.getInstance().logInWithReadPermissions(it, Arrays.asList(EMAIL, USER_POSTS, PUBLIC_PROFILE))
        }
    }

    override fun loginRequest(context: Activity, authToken: String) {
        super.loginRequest(context, authToken)
        weakReference?.get()?.toast("Facebook log in success authToken = $authToken")
        log("Facebook log in success authToken = $authToken")
    }


}